﻿@using System.ComponentModel.DataAnnotations

<MContainer>
    <MRow Justify="JustifyTypes.SpaceBetween">
        <MCol Cols="12"
              Md="4">
            <MForm @ref="_form">
                <MTextField @bind-Value="Model"
                            Rules="ModelRules"
                            Counter="Convert.ToInt32(_max)"
                            Label="First name"></MTextField>
            </MForm>
        </MCol>

        <MCol Cols="12"
              Md="6">
            <MSlider @bind-Value="Max"
                     Label="Max characters">
            </MSlider>

            <MCheckbox @bind-Value="_allowSpaces"
                       Label="Allow spaces"></MCheckbox>

            <MTextField @bind-Value="Match"
                        Label="Value must match"></MTextField>
        </MCol>
    </MRow>
</MContainer>

@code {
    private MForm _form;
    private string _model;
    private string _match;
    private bool _allowSpaces;
    private double _max;

    protected string Match
    {
        get
        {
            return _match;
        }
        set
        {
            _match = value;
            _form.Validate();
        }
    }

    protected double Max
    {
        get
        {
            return _max;
        }
        set
        {
            _max = value;
            _form.Validate();
        }
    }

    protected string Model
    {
        get
        {
            return _model;
        }
        set
        {
            _model = value;
            _form.Validate();
        }
    }

    protected List<Func<string, StringBoolean>> ModelRules
    {
        get
        {
            var rules = new List<Func<string, StringBoolean>>();

            if (Max > 0)
            {
                Func<string, StringBoolean> rule = v => v?.Length <= Max ? true : $"A maximum of {Max} characters is allowed";
                rules.Add(rule);
            }

            if (!_allowSpaces)
            {
                Func<string, StringBoolean> rule = v => v?.IndexOf(' ') < 0 ? true : "No spaces are allowed";
                rules.Add(rule);
            }

            if (!string.IsNullOrEmpty(Match))
            {
                Func<string, StringBoolean> rule = v => !string.IsNullOrEmpty(v) && v == Match ? true : "Values do not match";
                rules.Add(rule);
            }

            return rules;
        }
    }
}
